//
//  FilterVideoController.swift
//  BTVideo
//
//  Created by DouLei on 2019/8/15.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import RealmSwift
import SwifterSwift



class ST_BTHomeFilterVideoController: UIViewController {

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        root_view.roundCorners([UIRectCorner.topLeft,UIRectCorner.topRight], radius: 16)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let topEdge = iPhoneXSeries ? 87+statusBarHeight-20 : 87
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalToSuperview().offset(topEdge)
        }
        
        root_view.addSubview(root_scroll_view)
        root_scroll_view.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalToSuperview()
        }
        
        
        root_scroll_view.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalToSuperview()
            make.width.equalTo(2*ScreenWidth)
            make.height.equalTo(ScreenHeight-topEdge)
        }
        
        contentView.addSubview(mainView)
        mainView.snp.makeConstraints { (make) in
            make.top.left.bottom.equalToSuperview()
            make.width.equalTo(ScreenWidth)
        }
        
        contentView.addSubview(optionView)
        optionView.snp.makeConstraints { (make) in
            make.top.right.bottom.equalToSuperview()
            make.width.equalTo(ScreenWidth)
        }
     
        
        mainView.addSubview(close_btn)
        close_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(-3)
            make.width.height.equalTo(44)
        }
        
        mainView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(close_btn.snp.bottom).offset(4)
        }
        
        mainView.addSubview(reset_btn)
        reset_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(titleLabel)
            make.left.equalToSuperview().offset(8)
            make.width.height.equalTo(44)
        }
        
        mainView.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(titleLabel)
            make.right.equalToSuperview().offset(-8)
            make.width.height.equalTo(44)
        }
        
        mainView.addSubview(main_content_scroll_view)
        main_content_scroll_view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(34)
        }
        
        main_content_scroll_view.addSubview(main_content_view)
        main_content_view.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(600)
        }
        
        main_content_view.addSubview(sub_base_label)
        sub_base_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.top.equalToSuperview()
        }
        
        
        main_content_view.addSubview(genderItem)
        genderItem.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(sub_base_label.snp.bottom).offset(5)
            make.height.equalTo(60)
        }
        
        main_content_view.addSubview(ageItem)
        ageItem.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(genderItem.snp.bottom)
            make.height.equalTo(92)
        }
        
        main_content_view.addSubview(direction_item)
        direction_item.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(ageItem.snp.bottom)
            make.height.equalTo(92)
        }
        
        main_content_view.addSubview(advanced_label)
        advanced_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.top.equalTo(direction_item.snp.bottom).offset(16)
        }
        
        main_content_view.addSubview(ST_ZodiacItem)
        ST_ZodiacItem.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(advanced_label.snp.bottom).offset(5)
            make.height.equalTo(60)
        }
        
        main_content_view.addSubview(idealItem)
        idealItem.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(ST_ZodiacItem.snp.bottom)
            make.height.equalTo(60)
        }
        
        main_content_view.addSubview(statureItem)
        statureItem.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(idealItem.snp.bottom)
            make.height.equalTo(60)
        }
        
        main_content_view.addSubview(sexual_orientation_item)
        sexual_orientation_item.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(statureItem.snp.bottom)
            make.height.equalTo(60)
        }
        
        setUpData()
    }
    
    let realm = try! Realm()
    
//    必须为非空
    var current_filter:ST_DefaultFilterOfVideo!
    
    func setUpData(){
        
//        查询 保存的记录 isResetData = false
        if let first = realm.objects(ST_DefaultFilterOfVideo.self).filter("isResetData = false").first{
            
            self.current_filter = first.detached()
            
            bing_default_filter()
            return
        }
        
        JVrequest(PH.filterDefaultApi, success: { (json) in
            
            
            print("打印c当前返回的筛选:",json)
            
            let data = json["data"]
            
//            补充所有数据  ，
            
            let videoFIlterModel = ST_DefaultFilterOfVideo()
            
            let sex = ST_FilterOptionSelectModel()
            let s = ST_SEX.init(rawValue: data["gender"].intValue) ??  ST_SEX.both
            sex.selectedText = s.sexStr()
            sex.selectedId = s.rawValue.string
            sex.optionKey = "gender"
            sex.title = "性别"
            videoFIlterModel.sex = sex
            
            
            let age = ST_FilterOptionRangeModel()
            age.optionKey = "age"
            age.title = "年龄"
            //    两个值使用 minValue ... maxValue
            age.minValue = data["age"][0].intValue
            age.maxValue = data["age"][1].intValue
            
            videoFIlterModel.age = age
            
            let direction = ST_FilterOptionRangeModel()
            direction.optionKey = "distance"
            direction.title = "距离"
            direction.slideValue = data["distance"][1].intValue
            
            videoFIlterModel.direction = direction
            
            let ST_Zodiac = ST_FilterOptionSelectModel()
            ST_Zodiac.optionKey = "constellation"
            ST_Zodiac.title = "星座"
            
            videoFIlterModel.ST_Zodiac = ST_Zodiac
            
            
            
            let ideal = ST_FilterOptionSelectModel()
            ideal.optionKey = "personal_want"
            ideal.title = "想要寻求"
            videoFIlterModel.ideal = ideal
            
            let stature = ST_FilterOptionSelectModel()
            stature.optionKey = "personal_figure"
            stature.title = "身材"
            videoFIlterModel.stature = stature
            
            let sexualOrientation = ST_FilterOptionSelectModel()
            sexualOrientation.optionKey = "personal_like"
            sexualOrientation.title = "性取向"
            videoFIlterModel.sexualOrientation = sexualOrientation
            
            videoFIlterModel.isResetData = false
            let resetModel  = videoFIlterModel.detached()
            resetModel.isResetData = true
            //            APP全局只需要保存一次
            try! self.realm.write {
                self.realm.add(videoFIlterModel)
                self.realm.add(resetModel)
            }
                    
            self.current_filter = videoFIlterModel.detached()
            
            self.bing_default_filter()
            
        }) { (code, err) in
            
            print("默认筛选 -接口错误啦----",err)
            
        }
        
        
        
        
    }
    
    func bing_default_filter()  {
        
        genderItem.bind(model: self.current_filter.sex!)
        
        ageItem.bind(model: self.current_filter.age!)
        
        direction_item.bind(model: self.current_filter.direction!)
        
        ST_ZodiacItem.bind(model: self.current_filter.ST_Zodiac!)
        
        idealItem.bind(model: self.current_filter.ideal!)
        
//        statureItem.bind(model: self.current_filter.stature!)
        
        sexual_orientation_item.bind(model: self.current_filter.sexualOrientation!)
        
    }
    
//    MARK: - Properties
    
    lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
//        control.isScrollEnabled = false
        return control
    }()
    
    lazy var root_scroll_view:UIScrollView = {
        let control = UIScrollView()
//        control.backgroundColor = Color.random
        control.isScrollEnabled = false
        return control
    }()
    
    lazy var contentView:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        return control
    }()
    
    lazy var mainView:UIView = {
        let control = UIView()
//        control.backgroundColor = Color.random
        return control
    }()
    
    lazy var optionView:ST_FilterOptionSelectView = {
        let control = ST_FilterOptionSelectView()
//        control.backgroundColor = Color.random
        control.close_click_closure = { [weak self] m in
         
            self?.root_scroll_view.setContentOffset(CGPoint.zero, animated: true)
            
            if let model = m{
                switch model.optionKey {
                case "gender":
                    self?.current_filter.sex?.selectedText = model.selectedText
                    self?.current_filter.sex?.selectedId = model.selectedId
                case "constellation":
                    self?.current_filter.ST_Zodiac?.selectedText = model.selectedText
                    self?.current_filter.ST_Zodiac?.selectedId = model.selectedId
                case "personal_want":
                    self?.current_filter.ideal?.selectedText = model.selectedText
                    self?.current_filter.ideal?.selectedId = model.selectedId
                case "personal_figure":
                self?.current_filter.stature?.selectedText = model.selectedText
                self?.current_filter.stature?.selectedId = model.selectedId
                default: //personal_like
                    
                    self?.current_filter.sexualOrientation?.selectedText = model.selectedText
                    self?.current_filter.sexualOrientation?.selectedId = model.selectedId
                    break
                }
                self?.bing_default_filter()
            }
            
        }
        return control
    }()
    
    
    lazy var close_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("IndexItem_icon_收起")!)
        control.addTarget(self, action: #selector(close_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    lazy var confirm_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("确定")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#FEC207")!)
        control.addTarget(self, action: #selector(confirm_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    lazy var reset_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("清除")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#999999")!)
        control.addTarget(self, action: #selector(reset_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "向我展示"
        control.textColor = Color.init(hexString: "#333333")
//        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    lazy var main_content_scroll_view:UIScrollView = {
        let control = UIScrollView()
        return control
    }()
    
    lazy var main_content_view:UIView = {
        let control = UIView()
        return control
    }()
    
    lazy var sub_base_label:UILabel = {
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "基础")
        label.frame = CGRect(x: 25, y: 188, width: 28, height: 20)
        label.numberOfLines = 0
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    
    lazy var genderItem:ST_FilterVIdeoItemView = {
        let control = ST_FilterVIdeoItemView()
        
        control.pushOptionClosure = { m in
            
            self.optionView.request_data(optionModel: m)
            
            self.root_scroll_view.setContentOffset(CGPoint.init(x: ScreenWidth, y: 0), animated: true)
        }
        
        return control
    }()
    
    
    lazy var ageItem:ST_FilterRangeSliderItemView = {
        
        let control = ST_FilterRangeSliderItemView()
        control.didChange = {[weak self] min,max in
            self?.current_filter.age?.minValue = min
            self?.current_filter.age?.maxValue = max
        }
        return control
    }()
    
    
    
    lazy var direction_item:ST_FilterSliderItemView = {
        let control = ST_FilterSliderItemView()
        control.didChange = {[weak self] value in
            self?.current_filter.direction?.slideValue = value
        }
        return control
    }()
    
    
    
    lazy var advanced_label:UILabel = {
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "高级")
        label.frame = CGRect(x: 25, y: 188, width: 28, height: 20)
        label.numberOfLines = 0
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        return label
    }()
    
    
    
    lazy var ST_ZodiacItem:ST_FilterVIdeoItemView = {
        
        let control = ST_FilterVIdeoItemView()
        control.pushOptionClosure = { m in
            
            
            
            
            self.optionView.request_data(optionModel: m)
            
            self.root_scroll_view.setContentOffset(CGPoint.init(x: ScreenWidth, y: 0), animated: true)
        }
        return control
    }()
    
    
    lazy var idealItem:ST_FilterVIdeoItemView = {
        
        let control = ST_FilterVIdeoItemView()
        control.pushOptionClosure = { m in
            
            self.optionView.request_data(optionModel: m)
            
            self.root_scroll_view.setContentOffset(CGPoint.init(x: ScreenWidth, y: 0), animated: true)
        }
        return control
    }()
    
    lazy var statureItem:ST_FilterRangeSliderItemView = {
        
        let control = ST_FilterRangeSliderItemView()
//        control.pushOptionClosure = { m in
//
//            self.optionView.request_data(optionModel: m)
//
//            self.root_scroll_view.setContentOffset(CGPoint.init(x: ScreenWidth, y: 0), animated: true)
//        }
        return control
    }()
    
    
    lazy var sexual_orientation_item:ST_FilterVIdeoItemView = {
        
        let control = ST_FilterVIdeoItemView()
        control.pushOptionClosure = { m in
            
            self.optionView.request_data(optionModel: m)
            
            self.root_scroll_view.setContentOffset(CGPoint.init(x: ScreenWidth, y: 0), animated: true)
        }
        return control
    }()

    
    
//    MARK: - Event
    @objc func close_click_handle(){
        
        goback_previous_controller()
        
    }
    
    @objc func reset_handle(){
        
        if let obj = realm.objects(ST_DefaultFilterOfVideo.self).filter("isResetData = true").first{
            
            self.current_filter = obj.detached()
            self.current_filter.isResetData = false
            bing_default_filter()
            
        }
        
        
    }
    
    var refresh_closure:(()->())?
    
    @objc func confirm_handle(){
        
        let objects = realm.objects(ST_DefaultFilterOfVideo.self).filter("isResetData = false")
        
        try! realm.write {
            realm.delete(objects)
            realm.add(self.current_filter.detached())
        }
        
        refresh_closure?()
        goback_previous_controller()
        
    }
    
}





